import React, { PureComponent } from 'react'
import {
  Layout,
  Menu,
  Breadcrumb,
  Card,
  Avatar,
  Dropdown,
  Modal,
  message,
} from 'antd'
import {
  UnorderedListOutlined,
  SearchOutlined,
  BellOutlined,
  DownOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { NavLink, Router } from 'react-router-dom'
import { renderRoutes } from 'react-router-config'
import { history } from '@/index'
import breadcrumbNameMap from '@/Utils/BreadcrumbName'
import SliderBarConfig from '@/Utils/SliderBarConfig'
import routerConfig from './Routes'
import './HomePage.css'
import lebataImg from './Static/lebetaIcon.png'
const { SubMenu } = Menu
const { Header, Content, Sider } = Layout
export default class App extends PureComponent {
  state = {
    collapsed: false,
    sliderBar: null,
    selectedKeys: null,
    openKeys: null,
    signOutModalVisible: false,
    defaultOpenKeys: null,
    selectedData: null,
  }

  componentWillMount() {
    if (
      window.location.href.includes('/goodsInfo') ||
      window.location.href.includes('/orderMessage')
    ) {
      // 如果是衍生页面，则跳转到首页
      history.push('/homePage')
    }
  }

  componentDidMount() {
    const sliderBar = this.createMenu(SliderBarConfig())
    this.setState({
      sliderBar,
    })
  }

  componentDidUpdate() {
    this.getDefaultPage()
    if (!window.location.href.includes('/orderManagement')) {
      sessionStorage.removeItem('currentPage')
    }
  }

  handleOk = () => {
    history.push('/')
  }

  handleCancel = () => {
    this.setState({
      signOutModalVisible: false,
    })
  }

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    })
  }

  getDefaultPage() {
    let url = window.location.href
    url = '/' + url.substring(url.indexOf('/homePage/') + 1)
    const lastHref = url.split('/').pop()
    if (url === lastHref) {
      this.setState({
        selectedKeys: url,
        openKeys: null,
      })
    } else {
      this.setState({
        selectedKeys: url,
        openKeys: url.substring(url.indexOf('/'), url.lastIndexOf('/')),
      })
    }
  }

  // 解析侧边栏
  createMenu(menu = []) {
    return menu.map((item) => {
      if (item.children) {
        return (
          <SubMenu key={item.key} title={item.text} icon={item.icon}>
            {this.createMenu(item.children)}
          </SubMenu>
        )
      } else {
        return (
          <Menu.Item key={item.key} icon={item.icon}>
            <NavLink to={item.path}>{item.text}</NavLink>
          </Menu.Item>
        )
      }
    })
  }

  menu = (
    <Menu style={{ transform: 'translate(0,-15px)' }}>
      <Menu.Item key="0">
        <div
          onClick={() => {
            this.setState({
              signOutModalVisible: true,
            })
          }}
        >
          退出登录
        </div>
      </Menu.Item>
    </Menu>
  )

  createBreadcrumbs() {
    const pathSnippets = window.location.pathname.split('/').filter((i) => i)
    const extraBreadcrumbItems = pathSnippets.map((_, index) => {
      const url = `/${pathSnippets.slice(0, index + 1).join('/')}`
      if (index === 1 || index === pathSnippets.length - 1) {
        return (
          <Breadcrumb.Item key={url} style={{ cursor: 'not-allowed' }}>
            {breadcrumbNameMap[url]}
          </Breadcrumb.Item>
        )
      } else {
        return (
          <Breadcrumb.Item key={url}>
            <NavLink to={url}>{breadcrumbNameMap[url]}</NavLink>
          </Breadcrumb.Item>
        )
      }
    })

    return extraBreadcrumbItems
  }

  render() {
    const sliderBar = this.state.sliderBar
    const userInfo = JSON.parse(localStorage.getItem('userMessage')).userInfo
    return (
      <Router history={history}>
        {/* 顶部 */}
        <Header className="header" style={{ padding: 0 }}>
          {
            <div className="system-header">
              <div className="system-title">
                <img src={lebataImg} alt="" className="system-title-icon"></img>
                <div className="system-title-name">LeBeta Robot</div>
              </div>
              <div className="system-header-right">
                <UnorderedListOutlined></UnorderedListOutlined>
                <div className="right">
                  <SearchOutlined></SearchOutlined>
                  <BellOutlined></BellOutlined>

                  <Dropdown overlay={this.menu} trigger={['click']}>
                    <div className="user-menu">
                      <Avatar size="small" icon={<UserOutlined />} />
                      {userInfo.name}
                      <DownOutlined />
                    </div>
                  </Dropdown>
                  <div></div>
                </div>
              </div>
            </div>
          }
        </Header>
        <Layout>
          {/* 侧边栏 */}
          <Sider
            trigger={null}
            className="site-layout-background"
            collapsible
            collapsed={this.state.collapsed}
            style={{
              overflow: 'auto',
            }}
          >
            <Menu
              mode="inline"
              forceSubMenuRender={true}
              selectedKeys={this.state.selectedKeys}
              defaultSelectedKeys={this.state.openKeys}
            >
              {sliderBar}
            </Menu>
          </Sider>
          {/* 内容区 */}
          <Layout className="site-layout">
            <Breadcrumb style={{ margin: '16px 0' }} separator=">">
              {this.createBreadcrumbs()}
            </Breadcrumb>
            <Card>
              <Content>{renderRoutes(routerConfig)}</Content>
            </Card>
          </Layout>
        </Layout>
        <Modal
          title="提示"
          visible={this.state.signOutModalVisible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <p>是否确定要退出系统?</p>
        </Modal>
      </Router>
    )
  }
}
